#include "HttpGetRequest.h"

#include <iostream>
#include <stdlib.h>

#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"

using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::StreamCopier;
using Poco::Exception;

string HttpGetRequest::HTTP_GET  = HTTPRequest::HTTP_GET;
string HttpGetRequest::HTTP_POST  = HTTPRequest::HTTP_POST;

HttpGetRequest::HttpGetRequest(const string& method, const string& serverAddress, unsigned short port, const string& path)
{
    // The response should contain a custom header: resource: [resource id]
	HTTPResponse response;
	HTTPClientSession session(serverAddress, port);
	HTTPRequest request(method, path, HTTPMessage::HTTP_1_1);
	session.sendRequest(request);
    istream& rs = session.receiveResponse(response);
    if(response.has(RESOURCE_HEADER))
    {
        this->resource = atoi(response[RESOURCE_HEADER].c_str());
    }else
    {
        this->resource = INVALID_RESOURCE_ID;
    }
    StreamCopier::copyToString(rs,this->response); // default bufferSize = 8192
	this->reason = response.getReason();
	this->statusCode = response.getStatus();
    
    if(this->statusCode != 200 && this->statusCode != 204)
    {
        throw Exception(string("HttpGetRequest got invalid status code on path: ") + path);      
    }
    
}

unsigned int HttpGetRequest::getStatus()
{
	return this->statusCode;
}
string HttpGetRequest::getReason()
{
	return this->reason;
}

string HttpGetRequest::getResponse()
{
	return this->response;
}

vector<unsigned char> HttpGetRequest::getResponseVector()
{
	return vector<unsigned char>(this->response.begin(), this->response.end());
}

int HttpGetRequest::getResourceId()
{
	return this->resource;
}